<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select
            filterable
            placeholder="选择门店"
            v-model="formInline.store_id"
            @change="storeChange"
          >
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-model="formInline.is_effective" filterable style="width:100px">
            <el-option
              v-for="item in effective_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
        <el-form-item class="pull-right">
          <el-button type="primary" @click="addEditDialog=true">新增星星卡套餐</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="套餐名称"></el-table-column>
        <el-table-column align="center" prop="money" label="充值金额"></el-table-column>
        <el-table-column align="center" prop="stars" label="获得星星数"></el-table-column>
        <el-table-column align="center" label="生效时间" width="262">
          <template slot-scope="scope">{{ scope.row.effect_time+' - '+scope.row.stop_time }}</template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="240">
          <template slot-scope="scope">
            <el-button
              type="success"
              size="mini"
              v-if="scope.row.is_enable==1"
              @click="enableClick(scope.row)"
            >已启用</el-button>
            <el-button size="mini" v-else @click="enableClick(scope.row)">已停用</el-button>
            <el-button
              @click="delClick(scope.row.id,scope.$index)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <el-button type="primary" plain size="mini" @click="deployStoreClick(scope.row)">配置门店</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 套餐新增编辑弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        width="390px"
        title="新增星星卡套餐"
        :visible.sync="addEditDialog"
        append-to-body
        @close="callOf('saveForm')"
      >
        <el-form :model="saveForm" :rules="rules" ref="saveForm" class="demo-form-inline">
          <el-form-item label="套餐名称" prop="name">
            <el-input
              :maxlength="20"
              onkeypress="return event.which!=32"
              placeholder="请输入套餐名称(二十字内)"
              v-model="saveForm.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="充值金额" prop="money">
            <el-input
              placeholder="请输入充值金额"
              onkeypress="return event.which>=48&&event.which<=57"
              v-model="saveForm.money"
            ></el-input>
          </el-form-item>
          <el-form-item label="获得星星" prop="coins">
            <el-input
              placeholder="请输入获得星星"
              onkeypress="return event.which>=48&&event.which<=57"
              v-model="saveForm.coins"
            ></el-input>
          </el-form-item>
          <el-form-item label="生效日期" prop="pickerDate">
            <el-date-picker
              v-model="saveForm.pickerDate"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveClick('saveForm')" size="small">保存配置</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 配置门店弹框 -->
    <el-dialog :close-on-click-modal="false" width="650px" title="选择门店" :visible.sync="storeDialog">
      <div v-if="storeDialog">
        <div class="el-transfer-panel pull-left transferHeader">选择门店</div>
        <div class="el-transfer-panel pull-right transferHeader">已选门店</div>
      </div>
      <el-transfer
        :props="{key: 'id', label: 'name'}"
        :titles="['全选', '全选']"
        :button-texts="['删除', '添加']"
        filterable
        v-model="check_store_list"
        :data="t_store_list"
        ref="transfer"
        :left-default-checked="leftChecked"
        :right-default-checked="rightChecked"
        @change="checkStoreChange"
      ></el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button :disabled="btnDisabled" size="small" type="primary" @click="saveStoreClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getList,
  getStoreList,
  save_card_renewal,
  enable_card_renewal,
  savePackage,
  del,
  saveStore,
} from "@/api/member/rechargeCard";
import { num0to999999, nullto999999 } from "@/utils/validate";
import { pickerOptionsAfterF } from "@/utils";
export default {
  data() {
    const validateVal = (rule, value, callback) => {
      if (!num0to999999(value)) {
        callback(new Error("请输入0-999999整数"));
      } else {
        callback();
      }
    };
    return {
      btnDisabled: false,
      storeDialog: false,
      list: null,
      effective_list: [
        { id: "1", name: "有效套餐" },
        { id: "0", name: "失效套餐" },
      ],
      addEditDialog: false,
      listLoading: false,
      storeList: null,
      formInline: {
        store_id: "",
        is_effective: "1",
        type: "4",
      },
      saveForm: {
        name: "",
        type: "4",
        money: "",
        coins: "",
        effect_time: "",
        stop_time: "",
        pickerDate: [],
        type_id: "8",
      },
      saveStore: {
        store_list: [],
        id: "",
      },
      t_store_list: [],
      check_store_list: [],
      rightChecked: [],
      leftChecked: [],
      rules: {
        name: [{ required: true, message: "请输入套餐名称", trigger: "blur" }],
        type_id: [
          { required: true, message: "请选择卡类型", trigger: "change" },
        ],
        money: [{ required: true, validator: validateVal, trigger: "blur" }],
        coins: [{ required: true, validator: validateVal, trigger: "blur" }],
        pickerDate: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
      },
      pickerOptions: pickerOptionsAfterF(),
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.storeList) {
        vm.getStore();
      }
    });
  },
  methods: {
    checkStoreChange() {
      this.btnDisabled = false;
    },
    deployStoreClick(row) {
      this.t_store_list = this.storeList.filter(
        (item) => item.name !== "全门店"
      );
      this.btnDisabled = false;
      this.storeDialog = true;
      this.rightChecked = [];
      this.leftChecked = [];
      setTimeout(() => {
        this.$refs.transfer.clearQuery("left");
        this.$refs.transfer.clearQuery("right");
      }, 0);
      this.saveStore.id = row.id;
      this.saveStore.type = this.formInline.type;
      this.check_store_list = row.store_list.map((val) => val.id);
    },
    saveStoreClick() {
      this.saveStore.store_list = JSON.parse(
        JSON.stringify(this.check_store_list)
      );
      saveStore(this.saveStore)
        .then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          this.fetchData();
          this.storeDialog = false;
        })
        .catch((err) => {
          if (err.code) {
            this.btnDisabled = true;
            this.$message({
              type: "error",
              message: "部分所选门店已配置充值套餐，请勿重复配置，请删除",
              duration: 5 * 1000,
            });
            this.rightChecked = err.list;
          }
        });
    },
    // 新增提交
    saveClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!nullto999999(this.saveForm.coins)) {
            this.$message({ type: "error", message: "星星只能为0-999999整数" });
            return;
          }
          this.saveForm.effect_time = this.saveForm.pickerDate[0];
          this.saveForm.stop_time = this.saveForm.pickerDate[1];
          this.saveForm.store_id = this.formInline.store_id;
          this.saveForm.type = this.formInline.type;
          let data = JSON.parse(JSON.stringify(this.saveForm));
          // console.log(data)
          savePackage(data).then((response) => {
            this.fetchData();
            this.addEditDialog = false;
            this.$message({
              type: response.code == 1 ? "success" : "error",
              message: response.message,
            });
          });
        }
      });
    },
    // 停用启用
    enableClick(row) {
      let text =
        row.is_enable == 1
          ? "是否停用套餐，停用后将立刻生效"
          : "是否启用套餐，启用后将立刻生效";
      this.$confirm(text, "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        let data = {
          is_enable: row.is_enable == 1 ? 0 : 1,
          id: row.id,
          type: this.formInline.type,
        };
        enable_card_renewal(data).then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          if (response.code == 1) {
            row.is_enable = row.is_enable == 1 ? 0 : 1;
          }
        });
      });
    },
    delClick(id, index) {
      this.$confirm(
        "删除套餐后，所配置门店将立即下架该套餐，是否继续",
        "提示",
        { confirmButtonText: "是", cancelButtonText: "否", type: "warning" }
      ).then(() => {
        let data = {
          is_del: 1,
          id: id,
          type: this.formInline.type,
        };
        del(data).then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          if (response.code == 1) {
            this.list.splice(index, 1);
          }
        });
      });
    },
    storeChange() {
      this.fetchData();
    },
    getStore() {
      getStoreList({ category_id: this.$route.meta.id }).then((response) => {
        this.storeList = response;
        let data = response.filter(
          (res) => res.id == this.$store.getters.optionId
        );
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        }
        this.fetchData();
      });
    },
    typeChange() {
      this.fetchData();
    },
    // 搜索
    searchClick() {
      this.fetchData();
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      getList(this.formInline)
        .then((response) => {
          this.list = response;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    callOf(formName) {
      this.saveForm.coins = "";
      this.addEditDialog = false;
      this.$refs[formName].resetFields();
    },
  },
};
</script>